/**
 * 文本溢出后自动显示...，只有显示...后才启动 Tooltip 的纯文本组件
 * 用法很简单，类似 <span /> 标签
 */

import React, { useState, useRef, useEffect } from 'react'
import { Tooltip } from 'antd'
import clsx from 'clsx'
import { TooltipPlacement } from 'antd/es/tooltip'

interface TextTruncateProps {
  placement?: TooltipPlacement
  className: string // 请通过 className 来设置最大宽度，如 w-40, w-2/4，如果在 flex 下面，自动撑满，设置为 flex-grow，外层不能加flex否则无法换行判断是否超长
  children: React.ReactNode
  onClick?: () => void
  lines?: number
}

export default function TextTruncate(props: TextTruncateProps) {
  const { className, children, placement = 'bottomLeft', lines = 1 } = props
  const textRef = useRef<HTMLDivElement>(null)
  const [isOverflowing, setIsOverflowing] = useState(false)

  useEffect(() => {
    function checkOverflow() {
      const current = textRef.current
      if (current) {
        const isOverflow = current.offsetHeight < current.scrollHeight
        setIsOverflowing(isOverflow)
      }
    }

    checkOverflow()
    window.addEventListener('resize', checkOverflow)
    return () => window.removeEventListener('resize', checkOverflow)
  }, [children])

  return (
    <Tooltip
      overlayClassName="text-xs" // 应用自定义样式类
      title={isOverflowing ? children : ''}
      placement={placement}
    >
      <div
        ref={textRef}
        className={clsx('typography-multiline-ellipsis', className)}
        style={{ '--line-clamp': lines } as React.CSSProperties}
        onClick={props.onClick}
      >
        {children}
      </div>
    </Tooltip>
  )
}
